from django import http
from django.contrib.auth.decorators import login_required, wraps

from meiduo_mall.utils.response_code import RETCODE


def login_required_json(view_func):
    '''
    判断用户是否登录的装饰器,病返回json
    :param view_func:
    :return:
    '''

    @wraps(view_func)
    def wrapper(request, *args, **kwargs):

        # 用户未登录,返回json
        if not request.user.is_authenticated():
            return http.JsonResponse({'code': RETCODE.SESSIONERR, 'errmsg': '用户未登录'})
        else:
            return view_func(request, *args, **kwargs)

    return wrapper


class LoginRequiredJSONMixin(object):
    '''判断用户是否登录,并返回json的Mixin类'''


    @classmethod
    def as_view(cls, **initkwargs):
        view = super().as_view(**initkwargs)
        return login_required_json(view)



class LoginRequiredMixin(object):
    '''验证是否登录的工具类'''
    @classmethod
    def as_view(cls, **initkwargs):

        view = super().as_view()

        return login_required(view)